import json
from copy import copy
from distutils.command.install import value

from .kea2_pb2_grpc import Kea2ControlServiceServicer
from .hypiumKea import Kea2_RPC
from .kea2_pb2 import BooleanResponse, ExecutionResponse

class Kea2ControlService(Kea2ControlServiceServicer):
    """
    Kea2ControlService provides methods to control the Kea2 server.
    """

    def Init(self, request, context):
        """
        Initialize the Kea2 server with the given request parameters.
        """
        self.kea2 = Kea2_RPC(
            device_sn=request.device_serial,
            root_dir=request.root_dir
        )
        return BooleanResponse(value=True)

    def Start(self, request, context):
        """
        Start the Kea2 server.
        """
        # Implementation of start logic
        self.kea2.start()
        return BooleanResponse(value=True)

    def ExecuteProp(self, request, context):
        """
        Execute a property on the Kea2 server.
        """
        # Implementation of execute property logic
        propExecInfo = copy(self.kea2.exec_prop())
        if not propExecInfo.propName:
            return ExecutionResponse(state="NoPropExecuted", exec_info="")
        if propExecInfo.state == "Completed":
            self.kea2.propExecManager.propExecInfo.clear()
        return ExecutionResponse(
            state=propExecInfo.state,
            exec_info=json.dumps({
                "propName": propExecInfo.propName,
                "api": propExecInfo.api_name,
                "args": str(propExecInfo.args),
            })
        )

    def Continue(self, request, context):
        """
        Continue execution on the Kea2 server.
        """
        propExecInfo = copy(self.kea2.exec_prop())
        if propExecInfo.state == "Completed":
            self.kea2.propExecManager.propExecInfo.clear()
        return ExecutionResponse(
            state=propExecInfo.state,
            exec_info=json.dumps({
                "propName": propExecInfo.propName,
                "api": propExecInfo.api_name,
                "args": str(propExecInfo.args),
            })
        )

    def TearDown(self, request, context):
        """
        Tear down the Kea2 server.
        """
        self.kea2.tearDown()